import React, {useEffect, useState} from 'react'
import {Divider, Button, Modal, Row, Col, Popconfirm, message} from 'antd'
import {connect} from 'umi'
import SelectUserModal from "@/pages/components/SelectUserModal"
import {getInsuranceEmployeeInfo, saveOrUpdateEmployeeSecurity} from '../../service'
import {PlusOutlined} from '@ant-design/icons'
import {employeeStatusList, insuranceStatusList} from "@/utils/constant";
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table'
import moment from 'moment'


const CreateForm = (props) => {
  const {onCancel, visible, current} = props;
  const [loading, setLoading] = useState(false)
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [securityUserItems, setSecurityUserItems] = useState([]);

  const reloadTable = () => {
    setLoading(true);
    getInsuranceEmployeeInfo(current.id).then(res => {
      let cacheUserItems = [];
      securityUserItems.forEach(userItem => {
        if (res.filter(item => item.oid.toString() === userItem.oid.toString()).length < 1)
          cacheUserItems.push(userItem)
      });
      setSecurityUserItems([...res, ...cacheUserItems]);
      setLoading(false);
    })
  };

  useEffect(() => {
    if (current && visible) {
      reloadTable();
    }
  }, [visible]);

  const onFormCancel = () => {
    setSecurityUserItems([]);
    onCancel()
  };

  const confirmSelectedUsers = (values) => {
    let needValues = [];
    values.forEach(item => {
      if (securityUserItems.filter(fItem => fItem.oid.toString() === item.oid.toString()).length < 1)
        needValues.push({
          oid: item.oid,
          code: item.code,
          name: item.name,
          orgname: item.orgname,
          unitname: item.unitname,
          jobname: item.jobname,
          employeestatus: item.employeestatus,
          hiredate: item.hiredate,
          insuranceId: current.id
        })
    });
    setSecurityUserItems([...securityUserItems, ...needValues]);
    setUserModalVisible(false);
  };

  const saveOrChangeStatus = (e, record, type = 1) => {
    record.status = type;
    saveOrUpdateEmployeeSecurity(record).then(res => {
      if (res.flag) {
        message.success('操作成功！');
        reloadTable();
      } else {
        message.error(res.error);
      }
    })
  };

  const remove = (e, record) => {

  };

  let columns = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '工号',
      dataIndex: 'code',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '公司',
      dataIndex: 'orgname',
    },
    {
      title: '部门',
      dataIndex: 'unitname',
    },
    {
      title: '岗位',
      dataIndex: 'jobname',
    },
    {
      title: '状态',
      dataIndex: 'employeestatus',
      render: (text, record) => {
        return text !== '-' ? employeeStatusList.find(item => (item.value === `${text}`))?.label : ''
      }
    },
    {
      title: '入职时间',
      dataIndex: 'hiredate',
      render: (text) => text !== '-' && moment(text).format('YYYY-MM-DD')
    },
    {
      title: '生效状态',
      dataIndex: 'status',
      valueEnum: {
        1: {text: insuranceStatusList[1].label, status: 'Success'},
        2: {text: insuranceStatusList[0].label, status: 'Default'},
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '150px',
      render: (text, record) => {
        return (
          <>
            {record.id ? '' : <a onClick={(e) => saveOrChangeStatus(e, record)}>保存</a>}
            {
              record.id && (record.status === 2 ?
                <a onClick={(e) => saveOrChangeStatus(e, record, 1)}>生效</a> :
                <>
                  <a onClick={(e) => saveOrChangeStatus(e, record, 2)}>失效</a>
                  <Divider type="vertical"/>
                  <Popconfirm title="是否确认删除？" cancelText='取消' okText='确认'
                              onConfirm={(e) => remove(e, record)}>
                    <a>删除</a>
                  </Popconfirm>
                </>)
            }
          </>
        )
      }
    },
  ];

  const renderFooter = () => <Button type="primary" onClick={() => onFormCancel()}>关闭</Button>;

  return (
    <Modal
      title='方案人员配置'
      width={'90%'}
      destroyOnClose
      visible={visible}
      footer={renderFooter()}
      onOk={onFormCancel}
      onCancel={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >

      <Row gutter={24}>
        <Col span={24}>
          <ProTable
            rowKey="oid"
            loading={loading}
            toolBarRender={false}
            columns={columns}
            dataSource={securityUserItems}
            search={false}
            pagination={false}
          />
        </Col>
        <Col span={24}>
          <Button style={{width: '100%', marginBottom: 8}} type="dashed" onClick={() => setUserModalVisible(true)}>
            <PlusOutlined/>
            新增成员
          </Button>
        </Col>
      </Row>

      <SelectUserModal
        selectType={1}
        visible={userModalVisible}
        handleOk={confirmSelectedUsers}
        handleCancel={() => setUserModalVisible(false)}
      />
    </Modal>
  )
};


export default connect(({user}) => ({}))(CreateForm)
